package com.alibaba.citrus.cr.price.ability.functions.entity.activity;


import com.alibaba.acm.shaded.com.google.common.collect.Lists;
import com.alibaba.citrus.cr.price.repository.ActivityQueryRepository;
import com.alibaba.citrus.cr.common.util.SpringContextUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.crforecastsales.domian.activitytitle.model.ActivityTitle;
import com.epoch.app.crpricecenter.dto.request.ParticipateActivityInfoRequest;
import com.epoch.app.crpricecenter.dto.response.ActivityViewResponse;
import com.epoch.app.crpricecenter.dto.response.CheckActivityInfoResponse;
import com.epoch.app.crpricecenter.model.dto.ActivityOptionViewResponse;
import com.epoch.app.crpricecenter.sdo.ActivityTitleSDO;
import lombok.Data;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: qiaojiange
 * @create: 2021/10/17
 * @Description 活动抬头实体
 */
@Data
public class ActivityTitleEntity {

    private static Log log = Log.getLogger(ActivityTitleEntity.class);

    /**
     * 活动抬头SDO
     */
    private ActivityTitleSDO activityTitleSDO;

    /**
     * 需要保存的标识，如果过程中发生了数据的修改，需要把该字段 needSaveFlag 置为 true;
     */
    private boolean needSaveFlag = false;

    /**
     * 活动查询资源库
     */
    private static ActivityQueryRepository activityQueryRepository = SpringContextUtil.getBean(ActivityQueryRepository.class);


    /**
     * 创建对象
     *
     * @param sdo
     * @return
     */
    public static ActivityTitleEntity of(ActivityTitleSDO sdo) {
        ActivityTitleEntity titleEntity = new ActivityTitleEntity();
        titleEntity.setActivityTitleSDO(sdo);
        return titleEntity;
    }


    /**
     * 是否有扩展抬头表
     *
     * @return
     */
    public boolean hasTitleExt() {
        /**
         * 当活动抬头表中的按组管控标示 为 x ,也需要用抬头表中的扩展表中的申请数量替换本表的中的活动申请数量和申请费用
         */
        if ("X".equalsIgnoreCase(activityTitleSDO.getControlByGroupFlag())) {
            return true;
        }
        return false;
    }

    /**
     * 获取 activityId
     *
     * @return
     */
    public String obtainActivityId() {
        return activityTitleSDO.getActivityId();
    }

    /**
     * 获取 controlByGroupFlag
     * @return
     */
    public String obtainControlByGroupFlag(){
        return activityTitleSDO.getControlByGroupFlag();
    }

    /**
     * 活动便签 id
     *
     * @return
     */
    public String obtainActivityNoteId() {
        return activityTitleSDO.getActivityNoteId();
    }

    /**
     * 活动形式说明
     *
     * @return
     */
    public String obtainFacadeCode() {
        return activityTitleSDO.getActivityFacadeCode();
    }

    public String obtainActivityNoteName() {
        return activityTitleSDO.getActivityNoteName();
    }

    public Long obtainApplyFee() {
        return activityTitleSDO.getApplyFee();
    }

    public Date obtainOrderStartDate() {
        return activityTitleSDO.getOrderStartDate();
    }

    public Date obtainOrderEndDate() {
        return activityTitleSDO.getOrderEndDate();
    }

    public String obtainActivityStatus() {
        return activityTitleSDO.getActivityStatus();
    }


    /**
     * 校验活动
     *
     * @param activityInfo
     * @param response
     */
    public void checkActivity(ParticipateActivityInfoRequest activityInfo, CheckActivityInfoResponse response) {
        checkOrderDate(activityInfo, response);
        if (!response.getCheckResult()) {
            return;
        }
        checkOrderDeliveryDate(activityInfo, response);
    }

    /**
     * 校验订单的交货时间
     *
     * @param activityInfo
     * @param response
     */
    private void checkOrderDeliveryDate(ParticipateActivityInfoRequest activityInfo, CheckActivityInfoResponse response) {
        /**
         * this.obtainOrderStartDate() < activityInfo.getActivityUseTime() < this.obtainOrderEndDate()
         * 校验交货开始时间
         */
        if (activityInfo.getDeliveryDate().before(this.obtainOrderStartDate())) {
            log.error("活动校验失败，订单交货时间在订单开始时间之前!交货时间:{0},订单开始时间:{1}",
                    activityInfo.getDeliveryDate(), this.obtainOrderStartDate());
            response.setCheckResult(false);
            response.setCheckMsg("订单交货时间不在订单时间范围内！");
            return;
        }

        /**
         *  校验交货结束时间
         */
        if (activityInfo.getDeliveryDate().after(this.obtainOrderEndDate())) {
            log.error("活动校验失败，订单使用时间在活动开始时间之前!交货时间:{0},订单结束时间:{1}",
                    activityInfo.getDeliveryDate(), this.obtainOrderEndDate());
            response.setCheckResult(false);
            response.setCheckMsg("订单交货时间不在订单时间范围内！");
        }
    }

    /**
     * 校验订单下单时间
     *
     * @param activityInfo
     * @param response
     */
    private void checkOrderDate(ParticipateActivityInfoRequest activityInfo, CheckActivityInfoResponse response) {

        /**
         * this.obtainActivityStartDate() <= activityInfo.getActivityUseTime() <= this.obtainActivityEndDate()
         * 校验活动开始时间
         */
        if (activityInfo.getActivityUseTime().before(this.obtainActivityStartDate())) {
            log.error("活动校验失败，订单使用时间在活动开始时间之前!订单使用时间:{0},活动开始时间:{1}",
                    activityInfo.getActivityUseTime(), this.obtainActivityStartDate());
            response.setCheckResult(false);
            response.setCheckMsg("订单使用时间不在活动时间范围内！");
            return;
        }

        /**
         * 校验活动结束时间
         */
        if (activityInfo.getActivityUseTime().after(this.obtainActivityEndDate())) {
            log.error("活动校验失败，订单使用时间在活动结束时间之后!订单使用时间:{0},活动结束时间:{1}",
                    activityInfo.getActivityUseTime(), this.obtainActivityEndDate());
            response.setCheckResult(false);
            response.setCheckMsg("订单使用时间不在活动时间范围内！");
        }
        response.setCheckResult(true);
    }

    /**
     * 获取活动结束时间
     *
     * @return
     */
    private Date obtainActivityEndDate() {
        return activityTitleSDO.getActivityEndDate();
    }

    /**
     * 获取活动开始时间
     *
     * @return
     */
    private Date obtainActivityStartDate() {
        return activityTitleSDO.getActivityStartDate();
    }

    /**
     * 保存方法
     */
    public void save() {
        //如果不需要保存，直接返回
        if (!needSaveFlag) {
            return;
        }

        //下面就是保存逻辑，当前测试覆盖不到，在用的时候自行开发。

    }

    /**
     * 分页查询活动列表数据
     *
     * @return
     */
    public Result<List<ActivityViewResponse>> queryPromotionPageList() {

       // ActivityTitleLoadListResponse activityTitleLoadListResponse = activityQueryRepository.loadPromotionPageList(this.activityTitleSDO);


        List<ActivityViewResponse> activityViewResponses = Lists.newArrayList();

    //    activityTitleLoadListResponse.getData().forEach(item -> {
       //     ActivityViewResponse activityViewResponse = new ActivityViewResponse();
        //    activityViewResponse.setActivityId(item.getActivityId());
//            activityViewResponse.setActivityName(item.getActivityNoteName());
//
//            //先展示编码，具体的desc，后面再去调主数据接口进行转换 todo...hanguo
//            activityViewResponse.setOrganizationDesc(item.getSalesOrganization());
//            activityViewResponse.setChannelDesc(item.getSalesChannel());
//            activityViewResponse.setClientName(item.getClientId());
//
//            //活动类型描述，后续再定义枚举类进行转换 todo...hanguo
//            activityViewResponse.setActivityTypeDesc(item.getActivityFacadeCode());
//
//            activityViewResponse.setActivityStartDate(item.getActivityStartDate());
//            activityViewResponse.setActivityEndDate(item.getActivityEndDate());

//            activityViewResponses.add(activityViewResponse);
//        });
//
//        Result<List<ActivityViewResponse>> result = Result.success(activityViewResponses);
//        result.setTotal(activityTitleLoadListResponse.getTatol());
//
//        return result;
        return null;
    }

    /**
     * 查询销售组织信息，为筛选框提供的接口
     *
     * @return
     */
    public List<ActivityOptionViewResponse> queryOrganization() {
        return null;
    }

    /**
     * 查询销售渠道信息，为筛选框提供的接口
     *
     * @return
     */
    public List<ActivityOptionViewResponse> queryChannel() {
        return null;
    }

    /**
     *获取客户外部编码list
     * @return
     */
    public Result<List<String>> queryCustomerCodes() {
       return activityQueryRepository.queryCustomerCodesByActivityId(this.activityTitleSDO);
    }

    /**
     * 获取活动和客户的对应关系
     * @param activityIds
     * @return
     */
    public Map<String, List<String>> queryActivityAndCustomerMap(List<String> activityIds) {
        Map<String, List<String>> map = new HashMap<>();

        List<ActivityTitle> activityTitles = activityQueryRepository.queryActivityAndCustomerMap(activityIds);

        Map<String, List<ActivityTitle>> activityMap = activityTitles.stream().collect(Collectors.groupingBy(ActivityTitle::getActivityId));

        activityMap.keySet().forEach(e -> {
            List<String> clientIds = activityMap.get(e).stream().map(ActivityTitle::getClientId).distinct().collect(Collectors.toList());
            map.put(e, clientIds);
        });

        return map;
    }

    /**
     * 获取活动类型
     * @return
     */
    public String obtainActivityType() {
        return this.activityTitleSDO == null ? this.activityTitleSDO.getActivityFacadeCode() : null;
    }

    /**
     * 获取货币
     * @return
     */
    public String obtainCurrency() {
        return this.activityTitleSDO == null ? this.activityTitleSDO.getCurrency() : null;
    }

    /**
     * 获取活动和客户的对应关系用于导出
     * @param activityIds
     * @return
     */
    public Map<String, List<String>> queryActivityAndCustomerMapForExport(List<String> activityIds) {
        Map<String, List<String>> map = new HashMap<>();

        List<ActivityTitle> activityTitles = activityQueryRepository.queryActivityAndCustomerMapForExport(activityIds);

        Map<String, List<ActivityTitle>> activityMap = activityTitles.stream().collect(Collectors.groupingBy(ActivityTitle::getActivityId));

        activityMap.keySet().forEach(e -> {
            List<String> clientIds = activityMap.get(e).stream().map(ActivityTitle::getClientId).distinct().collect(Collectors.toList());
            map.put(e, clientIds);
        });

        return map;
    }
}
